from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django import views
from rbac import models
from rbac.service.init_permission import init_permission
from django.conf import settings
from django.utils.module_loading import import_string


class Login(views.View):

    def get(self, request):
        return render(request, 'login.html')

    def post(self,request):
        name=request.POST.get('name')
        password=request.POST.get('password')
        user_class=import_string(settings.USER_MODEL_PATH)
        user_obj=user_class.objects.filter(name=name,password=password).first()
        if not user_obj:
            return render(request,'login.html',{'msg':'用户名或密码错误'})
        else:
            request.session['user_info']={'id':user_obj.id,'name':user_obj.name}
            init_permission(request,user_obj)
            return redirect('/rbac/home/')